# -*- encoding:utf-8 -*-

import os
from configparser import ConfigParser
from concurrent.futures import ProcessPoolExecutor
from pdfminer.converter import TextConverter, HTMLConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
from io import StringIO
from io import open
from docx import Document


def read_from_pdf(file_path):
    print(file_path)
    with open(file_path, 'rb') as file:
        resource_manager = PDFResourceManager()
        return_str = StringIO()
        lap_params = LAParams()

        device = TextConverter(resource_manager, return_str,
                               laparams=lap_params)
        process_pdf(resource_manager, device, file)
        device.close()
        content = return_str.getvalue()
        return_str.close()
        return content


def remove_control_characters(content):
    mpa = dict.fromkeys(range(32))
    return content.translate(mpa)


def convert_pdf_to_word(pdf_file_path, word_file_path):
    content = read_from_pdf(pdf_file_path)
    doc = Document()
    for line in content.split('\n'):
        paragraph = doc.add_paragraph()
        paragraph.add_run(remove_control_characters(line))
    doc.save(word_file_path)


def convert_pdf_to_word_under_folder(pdf_folder, word_folder, max_worker=5):
    assert pdf_folder is not None
    assert word_folder is not None
    tasks = []
    with ProcessPoolExecutor(max_workers=max_worker) as executor:
        for file in os.listdir(pdf_folder):
            print('file:', file)
            extension_name = os.path.splitext(file)[1]
            if extension_name != '.pdf':
                continue
            file_name = os.path.splitext(file)[0]
            pdf_file = os.path.join(pdf_folder, file)
            word_file = os.path.join(word_folder, file_name + '.docx')
            print('正在处理:', file)
            result = executor.submit(convert_pdf_to_word, pdf_file, word_file)
            tasks.append(result)
        while True:
            exit_flag = True
            for task in tasks:
                if not task.done():
                    exit_flag = False
            if exit_flag:
                print('完成')
                exit(0)


if __name__ == '__main__':
    # 解析本地PDF文本，保存到本地TXT
    paperPdfParser = convert_pdf_to_word(
        r'paper/A Novel Methodology of Time Dependent Mean Field Based Multilayer Unsupervised Anomaly Detection Using Traffic Surveillance Videos_-基于时变均值场的交通监控视频多层无监督异常检测新方法_.pdf',"a.docx")
